import 'dart:convert';

import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:sph_driver/AppConfig/LocalStorage.dart';

import '../AppConfig/Config.dart';
import '../AppConfig/RouteAct.dart';
import '../AppConfig/StringEncapsulation.dart';
import '../FindGoods/SourceDetails.dart';
import '../http/NoLoadingGetApi.dart';
import '../http/NoLoadingPostApi.dart';
import '../http/api.dart';
import '../l10n/messages.dart';

class RoteOfSource extends StatefulWidget {
  const RoteOfSource({super.key, required this.loadInfo, required this.unloadInfo});
  final Map loadInfo;
  final Map unloadInfo;
  @override
  State<RoteOfSource> createState() => _RoteOfSourceState();
}

class _RoteOfSourceState extends State<RoteOfSource> {
  List goodsList=[];
  Map sourceDetailsMap={};
  int pageNum=1;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    print(widget.loadInfo['areaCode']);
    getNewGoodsList();
  }
  //更新货源
  void getNewGoodsList() async {

    NoLoadinggetApiManager.getData(
      context, "api/goods/goods/driverRouteGoodsPage",
      {
        "current":1,
        "size":"20",
        "loadPlaceCode":widget.loadInfo['areaCode'],
        "unloadPlaceCode":widget.unloadInfo['areaCode'],
      },
          (responseData) async {
        setState(() {
            goodsList = responseData['data']['records'];

        });

      },
    );

  }

  //货源详情
  void getSourceDetailsAction(Map dataMap) async {
    String? drvId=await UserIdManager.getUserID();
    NoLoadinggetApiManager.getData(
      context,
      MyServiceUrl.getLoginUser,
      {},
          (responseData) async {
        Navigator.push( context, FadeRoute(page:SourceDetails(
          dataMap: dataMap,
        )));
      },
    );
  }
  Future _onRefresh() async {
    pageNum=1;
    getNewGoodsList();

  }
  Future _onLoadfresh() async{
    if(goodsList.length > 20*pageNum-1){
      pageNum++;
      getNewGoodsList();
    }

  }
  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    var messages = AppLocalizations.of(context)!;
    return Scaffold(
      backgroundColor: MyColors.backgreyColor,
      appBar: AppBar(
        title:Text( "配货路线货源",style: TextStyle(fontWeight: FontWeight.w300,fontSize: 16.sp),),
        backgroundColor: Colors.white,
        centerTitle: true,
        leading: IconButton(
          icon: Icon(Icons.arrow_back_ios, color: Colors.black),
          onPressed: () => Navigator.of(context).pop(),
        ),
        actions: [
          Badge(
            label:Text("1"),
            child:GestureDetector(
              child: Row(
                children: [

                  Image.asset("lib/Images/RoadLine/消息icon.png",width: 16.w,height: 16.h,),
                  SizedBox(width: 10.w,),
                ],
              ),
              onTap: (){

              },
            ),


          ),
        ],

      ),
    body: ListView(
    children: [
      EasyRefresh(
        header:
        ClassicHeader(
          dragText: '下拉刷新',
          armedText: '准备释放',
          readyText: '加载中...',
          processingText: '加载中...',
          processedText: '刷新成功',
          noMoreText: '暂无更多',
          failedText: '刷新失败',
          messageText: '刷新时间 %T',
        ),
        footer: ClassicFooter(
          dragText: '加载更多',
          armedText: '准备释放',
          readyText: '加载中...',
          processingText: '加载中...',
          processedText: '加载成功',
          noMoreText: '暂无更多',
          failedText: '加载失败',
          messageText: '加载时间 %T',
        ),
        onRefresh: _onRefresh,
        onLoad: goodsList.length > 20*pageNum-1?_onLoadfresh:null,
        child:
      goodsList.length==0?
      Container(
        height:screenSize.height,
        color: Colors.white,
        child:    ListView(
          children: [
            Center(
                child:   BrnAbnormalStateWidget(
                  img: Image.asset(
                    'lib/Images/OrderList/找货暂无货源.png',
                    scale: 3.0,
                  ),
                  content: '暂无货源',
                )
            )

          ],
        ),
      )

          :Container(
        color: MyColors.backgreyColor,
        height: screenSize.height-240.h,
        margin: EdgeInsets.only(top: 8.h),
        padding: EdgeInsets.only(left: 10.w,right: 10.w),

        child:  ListView.builder(
            padding: EdgeInsets.zero, // 设置padding为零
            shrinkWrap: true,
            itemCount:  goodsList.length,

            itemBuilder: (BuildContext context,
                int index) {
              return GestureDetector(
                child: Container(
                  margin: EdgeInsets.only(bottom: 8.h,),
                  padding: EdgeInsets.only(top: 8.h,bottom: 8.h,left: 10.w,right: 10.w),
                  decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.all(Radius.circular(10))),
                  child:Column(
                      children: [
                        Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            if(goodsList[index]['category']==1)
                              Image.asset("lib/Images/OrderList/企业标签.png",width: 30.w,height: 18.h,),
                            if(goodsList[index]['invoiceType']==1)
                              SizedBox(width: 8.w,),
                            if(goodsList[index]['invoiceType']==1)
                              Image.asset("lib/Images/OrderList/专票标签.png",width: 30.w,height: 18.h,),
                          ],
                        ),
                        Row(
                          children: [
                            Column(
                              children: [
                                Image.asset("lib/Images/OrderList/装icon.png",
                                  width: 13.w, height: 13.h,),
                                Image.asset(
                                  "lib/Images/OrderList/垂直虚线.png", width: 13.w,
                                  height: 10.h,),
                                if(goodsList[index]["loadPlaceInfo"].length == 2&&goodsList[index]["loadPlaceInfo"][1]!=null&&goodsList[index]["loadPlaceInfo"][1]!="null")
                                  Column(
                                    children: [
                                      Image.asset(
                                        "lib/Images/OrderList/装icon.png",
                                        width: 13.w, height: 13.h,),
                                      Image.asset(
                                        "lib/Images/OrderList/垂直虚线.png",
                                        width: 13.w, height: 10.h,),
                                    ],
                                  ),
                                if( goodsList[index]["unloadPlaceInfo"].length == 2&&goodsList[index]["unloadPlaceInfo"][1]!=null&&goodsList[index]["loadPlaceInfo"][1]!="null")
                                  Column(
                                    children: [
                                      Image.asset(
                                        "lib/Images/OrderList/卸icon.png",
                                        width: 13.w, height: 13.h,),
                                      Image.asset(
                                        "lib/Images/OrderList/垂直虚线.png",
                                        width: 13.w, height:10.h,),
                                    ],
                                  ),
                                Image.asset("lib/Images/OrderList/卸icon.png",
                                  width: 13.w, height: 13.h,),
                              ],
                            ),

                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,

                              children: [
                                Container(
                                  width: screenSize.width-60.w,
                                  child:   Row(
                                    children: [
                                      Container(
                                        constraints: BoxConstraints(
                                          maxWidth: 170.w, // 限制文本最大宽度
                                        ),
                                        child:    Text(
                                          goodsList[index]["loadPlaceInfo"][0]["city"] +
                                              " " +
                                              goodsList[index]["loadPlaceInfo"][0]["county"],
                                          style: TextStyle(color: Colors.black,
                                              fontSize: 13.sp,fontWeight: FontWeight.w600),),
                                      ),
                                      SizedBox(width: 4.w,),
                                      Container(
                                        constraints: BoxConstraints(
                                          maxWidth: screenSize.width - 84.w - 120.w, // 限制文本最大宽度
                                        ),
                                        child:   Text(goodsList[index]["loadDay"]+" "+goodsList[index]["loadTime"]+"点装货",overflow: TextOverflow.ellipsis, style: TextStyle(
                                            color:MyColors.textColor,
                                            fontSize: 12.sp),),
                                      ),
                                    ],
                                  ),
                                ),

                                SizedBox(height: 8.h,),
                                if(goodsList[index]["loadPlaceInfo"].length == 2&&goodsList[index]["loadPlaceInfo"][1]!=null&&goodsList[index]["loadPlaceInfo"][1]!="null")
                                  Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      Row(
                                        children: [
                                          Container(
                                            // width: screenSize.width/3,
                                            child:   Text(

                                              goodsList[index]["loadPlaceInfo"][1]["city"] +
                                                  "-" +
                                                  goodsList[index]["loadPlaceInfo"][1]["county"] ,
                                              style: TextStyle(
                                                  color: Colors.black, fontSize: 13.sp,overflow: TextOverflow.ellipsis,fontWeight: FontWeight.w600),),
                                          ),
                                        ],
                                      ),


                                      SizedBox(height: 8.h,),
                                    ],
                                  ),
                                Container(
                                  width: screenSize.width-60.w,
                                  child:   Row(
                                    children: [
                                      Container(
                                        constraints: BoxConstraints(
                                          maxWidth: 170.w, // 限制文本最大宽度
                                        ),
                                        child:    Text(
                                          goodsList[index]["unloadPlaceInfo"][0]["city"] +
                                              " " +
                                              goodsList[index]["unloadPlaceInfo"][0]["county"],
                                          style: TextStyle(color: Colors.black,
                                              fontSize: 13.sp,fontWeight: FontWeight.w600),),
                                      ),
                                      SizedBox(width: 4.w,),
                                      Container(
                                        constraints: BoxConstraints(
                                          maxWidth: screenSize.width - 84.w - 120.w, // 限制文本最大宽度
                                        ),
                                        child:   Text(goodsList[index]["unloadDay"]+" "+goodsList[index]["unloadTime"]+"点卸货",overflow: TextOverflow.ellipsis, style: TextStyle(
                                            color:MyColors.textColor,
                                            fontSize: 12.sp),),
                                      ),
                                    ],
                                  ),
                                ),

                                if(goodsList[index]["unloadPlaceInfo"].length == 2&&goodsList[index]["unloadPlaceInfo"][1]!=null&&goodsList[index]["unloadPlaceInfo"][1]!="null")
                                  Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      SizedBox(height: 8.h,),
                                      Row(
                                        children: [
                                          Container(
                                            // width: screenSize.width/3,
                                            child:
                                            Text(
                                              goodsList[index]["unloadPlaceInfo"][1]["city"] +
                                                  "-" +
                                                  goodsList[index]["unloadPlaceInfo"][1]["county"],
                                              style: TextStyle(overflow: TextOverflow.ellipsis,
                                                  color: Colors.black, fontSize: 13.sp,fontWeight: FontWeight.w600),),
                                          ),
                                          // SizedBox(width: 8.w,),

                                        ],
                                      ),


                                    ],
                                  ),

                              ],

                            ),

                          ],

                        ),
                        SizedBox(height:8.h),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Row(
                              children: [
                                SizedBox(width: 5.w,),
                                if( goodsList[index]["cargoInfo"][0]["cargoName"]!=null)
                                  Text(goodsList[index]["cargoInfo"][0]["cargoName"],  style: TextStyle(color: MyColors.textColor, fontSize: 13.sp),),
                                if( goodsList[index]["cargoInfo"][0]["cargoWeight"]!=null)
                                  Text(","+goodsList[index]["cargoInfo"][0]["cargoWeight"].toString() + "吨",  style: TextStyle(color: MyColors.textColor, fontSize: 13.sp),),
                                if( goodsList[index]["cargoInfo"][0]["cargoVolume"]!=null)
                                  Text( ","+goodsList[index]["cargoInfo"][0]["cargoVolume"].toString() + "方", style: TextStyle(color: MyColors.textColor, fontSize: 13.sp),),
                                if( goodsList[index]["cargoInfo"][0]["packageType"]!=null)
                                  Text( ","+goodsList[index]["cargoInfo"][0]["packageType"].toString(), style: TextStyle(color: MyColors.textColor, fontSize: 13.sp),),
                              ],
                            ),

                          ],
                        ),

                        Row(
                          children: [
                            SizedBox(width: 5.w,),
                            goodsList[index]["vehicleLength"].contains(",")?
                            Text( goodsList[index]["vehicleLength"].replaceAll(",", "米/")+"米",style: TextStyle(color: MyColors.textColor, fontSize: 13.sp),):
                            Text( goodsList[index]["vehicleLength"]+"米",style: TextStyle(color: MyColors.textColor, fontSize: 13.sp),),
                            if(goodsList[index]["vehicleModel"]!=null)
                              goodsList[index]["vehicleLength"].contains(",")?
                              Text("丨"+goodsList[index]["vehicleModel"].replaceAll(",", "/"),style: TextStyle(color: MyColors.textColor, fontSize: 13.sp),)
                                  : Text("丨"+goodsList[index]["vehicleModel"],style: TextStyle(color: MyColors.textColor, fontSize: 13.sp),),

                          ],
                        ),

                        int.parse(goodsList[index]["type"].toString()) == 0?
                        Row(
                          crossAxisAlignment: CrossAxisAlignment.end,
                          children: [
                            SizedBox(width: 5.w,),
                            Text((goodsList[index]["freight"]).toString(),
                              style: TextStyle(color: MyColors.themeColor,
                                  fontSize: 20.sp,
                                  fontWeight: FontWeight.w600),),
                            Column(
                              children: [
                                Text("元/趟",  style: TextStyle(
                                    color: MyColors.themeColor,
                                    fontSize: 12.sp,
                                    fontWeight: FontWeight.w600), ),
                                SizedBox(height: 3.h,),
                              ],
                            )


                          ],
                        )
                            :Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: [
                            Text("电议", style: TextStyle(
                                color: MyColors.themeColor,
                                fontSize: 20.sp,
                                fontWeight: FontWeight.w600),),
                          ],
                        ),
                        Divider(height: 1.h,color: MyColors.backgreyColor,),
                        SizedBox(height: 6.h,),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Row(
                              children: [
                                Container(
                                  decoration: BoxDecoration(
                                      color: Colors.white,
                                      borderRadius: BorderRadius.all(Radius.circular(10))),
                                  child: ClipRRect(
                                    borderRadius: BorderRadius.all(Radius.circular(10)),
                                    child: goodsList[index]['avatarPath']!=""&&goodsList[index]['avatarPath']!=null?Image.network(
                                      MyServiceUrl.imgHeader + goodsList[index]['avatarPath'],
                                      width: 36.w,
                                      height: 36.h,
                                      fit: BoxFit.cover,
                                    ):Image.asset("lib/Images/login/默认头像.jpeg",width: 36.w, height: 36.h, fit: BoxFit.cover,),
                                  ),
                                ),
                                SizedBox(width: 8.w,),
                                Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [

                                    Row(
                                      children: [
                                        if(goodsList[index]['realName']!=null)
                                          Text(goodsList[index]['realName'],style: TextStyle(color: Colors.black,fontSize: 13.sp),),
                                        SizedBox(width: 4.w,),
                                        if(goodsList[index]['rating']!=null)
                                          BrnTagCustom(
                                            tagText: "信用"+(divideAndRound(goodsList[index]['rating'], 20)).toString()+"星",
                                            backgroundColor: Color.fromRGBO(251, 236, 228, 1),
                                            textColor: MyColors.themeColor,
                                          ),
                                      ],
                                    ),
                                    if(goodsList[index]['totalNum']!=null&&goodsList[index]['rating']!=null)
                                      Text("交易  "+goodsList[index]['totalNum'].toString()+"  "+"好评率  "+goodsList[index]['rating']+"%"
                                        ,style: TextStyle(color: MyColors.textColor,fontSize: 12.sp),),
                                  ],
                                ),

                              ],
                            ),
                            BrnSmallMainButton(
                              title: '去抢单',
                              bgColor:MyColors.themeColor,
                              textColor:Colors.white,
                              width: 80.w,
                              fontSize: 13.sp,
                              radius:30,
                              onTap: ()  async {

                                getSourceDetailsAction(goodsList[index]);

                              },
                            )
                          ],
                        ),


                      ]
                  ),
                ),
                onTap: (){
                  // if(isCheck==false) {
                  getSourceDetailsAction(goodsList[index]);
                  // setState(() {
                  //   isCheck=true;
                  // });
                  // }

                },
              );
            }
        ),
      ),
    ),
    ],
    ),
    );
  }
}
